/**
 * Description:基于容器的表格 Copyright: 成都和为科技有限公司 2012 author:zhouxingxing
 * CreateDate: 2012-05-01
 * 
 * 属性： fillBlankRow - 是否以空白行填充表格。 默认为false 
 * 		rowNum - 每页显示记录条数, 默认10条 
 * 		noresult - 是否无结果给出提示。默认为false 
 * 		noresulttext - 无结果提示信息 
 * 		lazyLoad - 延迟加载每页数据。默认为true
 * 		pageable - 默认false.
 *      multiselect - 是否多选
 *      isshowrownum -默认true
 * 		
 * 事件：
 *     onload - 表格加载完成调用
 *     onpaging - 翻页调用事件
 *     beforeshow - 显示数据前调用
 *     onselectrow ：选择行
 *     onselectall : 选择所有
 */
function ComponentDataGrid() {
}

ComponentDataGrid.inherit(Container);

/**
 * 初始化方法
 */
ComponentDataGrid.prototype.init = function() {
	ComponentDataGrid.base.init.call(this);
}

ComponentDataGrid.prototype.initLoad = function() {
	debugger;
	ComponentDataGrid.base.initLoad.call(this);
	// 页数据条数
	this._rowNum = 10;
	this._isShowRowNum=true;
	if (this.getAttribute().rownum) {
		this._rowNum = parseInt(this.getAttribute().rownum);
	}
	//是否显示记录数
	if ("false"==this.getAttribute().isshowrownum||false==this.getAttribute().isshowrownum) {
		this._isShowRowNum = false;
	}
	//
	this._fillBlankRow = false;
	if (this.getAttribute().fillblankrow
			&& this.getAttribute().fillblankrow == "true") {
		this._fillBlankRow = true;
	}
	//
	this._noresult = false;
	if (this.getAttribute().noresult && this.getAttribute().noresult == "true") {
		this._noresult = true;
	}

	//表头增加选中按钮
	// 增加选择按钮
	if (this.getAttribute().multiselect &&
		this.getAttribute().multiselect == "true") {
		var that = this;
		var header = this.getElementById("header");
		if (header) {
			this._checkAllBtn = header.addItem("CheckBox", {
				"class":"table-checkbox",
				"onchange": function(oCheckBox) {
					if (typeof(oCheckBox) != "object") return;
					that.resetSelection();
				}
			});
			$(header.getHTML()).css("padding-left", "30px");
		}
	}

	// 行模板
	this._row = this.getElementById("row");
	this._row.getAttribute().datasource = "";
	this._row.hide();

	this._start = document.createElement("div"); // 表格内容容器
	$(this._start).hide();
	this._end = document.createElement("div"); // 表格内容容器
	$(this._end).hide();
	$(this._row.getHTML()).before(this._start);
	$(this._row.getHTML()).after(this._end);
	this.removeElement(this._row);
	// 表格数据
	this._data = new Array();
	//当前记录行
	this._records = new Object(); 
	//缓存记录行
	this._cache = new Object();
	//排序
	this._sort = "";
	if (this._fillBlankRow) {
		this.showPage(this._data);
	}
	if (this.getAttribute().params) {
        var sParam = this.getAttribute().params.replaceAll("'","\"");
        var oParam = JSON.parse(sParam);
        this._fixParam = oParam;
    }
    //加载分页
    if (this.getAttribute().pageable == "true") {
        this.loadPageTool();
    }
}

/**
 * 加载分页组件
 */
ComponentDataGrid.prototype.loadPageTool = function() {
    this._pageTool = this.addItem("Component", {
        src:"/public.common/comp/tablepagetool/TablePageTool.html"
    });
    this._pageHandler = this._pageTool.getHandleClass();
    this._pageHandler.postMessage({
        "id":"MSG_TABLEPAGETOOL_LOAD",
        "table":this
    });
}

/**
 * 显示表格
 *
 * @param Array
 *            结果数据数组
 */
ComponentDataGrid.prototype.showPage = function(oResult) {
	this.clear();
	/** 判断是否显示空记录结果提示 */
	if (this._noresult && oResult.length == 0) {
		this.showNoResult();
		return;
	}
	for (var i = 0; i < this._rowNum; i++) {
		if (oResult[i]) {//如果有数据绑定
			this.addRecord(oResult[i], i);
		} else {
			if (this._fillBlankRow) {
				this.addRecord({}, i);
			}
		}
	}
}

/**
 * 显示无结果记录
 */
ComponentDataGrid.prototype.showNoResult = function() {
	$("#no-result", this.getHTML()).remove();
	var noresulttext = "系统未查找到相应数据.";
	if (this.getAttribute().noresulttext) {
		noresulttext = this.getAttribute().noresulttext;
	}
	var template = "<div id='no-result' class='row'>"
			+ "<div class='no-result'>"
			+ "<span class='glyphicon glyphicon-exclamation-sign'></span>&nbsp;&nbsp;"
			+ noresulttext + "</div>" + "</div>";
	$(this.getHTML()).append(template);
}

/**
 * 表格中增加一行记录
 * @param {} oData 绑定数据。 无数据则加载记录
 * @param {} num 行号，如果不传，则自动增加
 */
ComponentDataGrid.prototype.addRecord = function(oData, num) {
	if (!num) {
		num = this.getDataRowCount();
	}
	//先取缓存，不存在则复制
	var cr = this.popRecord(num);
	if (!cr) {
		var cr = this._row.clone();
		// 增加选择按钮
		if (this.getAttribute().multiselect &&
			this.getAttribute().multiselect == "true") {
			var that = this;
			var oCheckBox = cr.addItem("CheckBox", {
				"path":"rowselect",
				"class":"table-checkbox",
				"onchange": function(oCheckBox, event) {
					if (typeof(oCheckBox) != "object") return;
					var row = oCheckBox.getParent();
					var id = row.getRowID();
					that.setSelection(id, true, true);
				},
				"click": function(oCheckBox, event) {
					if (event) {
						event.stopPropagation();
					}
				}
			});
			$(cr.getHTML()).css("padding-left", "30px");
		}
		cr.show();
		$(cr.getHTML()).css("display", "");
		this.pushRecord(cr, num);
	}
	$(this._end).before(cr.getHTML());
	if (oData) {
		oData.rownum = (num + 1); // 增加表格序号
		cr.setRowNum(num);
		cr.initForm(oData);
	}
	var id = oData.id;
	if (typeof(id) == "undefined" || this._records[id]) {
		id = Math.uuid();
	}
	this._records[id] = cr;
	cr.setRowID(id);
	this.modifyGroupName(cr);
	return cr;
}

/**
 * 修改单选和复选控件名称
 * @param {} cr
 */
ComponentDataGrid.prototype.modifyGroupName = function(cr) {
	//单选和复选修改GroupName属性
	var radioBtns = cr.getElementByType("RadioButton");
	for (var i = 0 ; i < radioBtns.length ; i++) {
		var groupName = radioBtns[i].getAttribute().groupname;
		radioBtns[i].setGroupName(cr.getRowID() + groupName);
	}
	//单选和复选修改GroupName属性
	var checkBtns = cr.getElementByType("CheckBox");
	for (var i = 0 ; i < checkBtns.length ; i++) {
		var groupName = checkBtns[i].getAttribute().groupname;
		checkBtns[i].setGroupName(cr.getRowID() + groupName);
	}
}

/**
 * 表格记录行缓存
 * @param {} oRecord
 * @param {} num
 */
ComponentDataGrid.prototype.pushRecord = function(oRecord, num) {
	this._cache[num] = oRecord;
}

/**
 * 取出缓存记录行
 * @param {} num
 */
ComponentDataGrid.prototype.popRecord = function(num) {
	return this._cache[num];
}

/**
 * 设置表格行的记录结果
 * @param {} oRecord
 * @param {} oData
 */
ComponentDataGrid.prototype.setRecord = function(oRecord, oData) {
	oRecord.clearForm();
	oRecord.initForm(oData);
	oRecord.setRowID(oData.id);
	$(this._end).before(oRecord.getHTML());
}

/**
 * 删除记录
 * @param {} rowid
 */
ComponentDataGrid.prototype.delRecord = function(rowid) {
	var oRow = this.getRow(rowid);
	this.delRow(oRow);
	this.showPage(this.getValue());
}

/**
 * 删除多条记录
 * @param {} rowids 数组
 */
ComponentDataGrid.prototype.delRecords = function(rowids) {
	for (var i = 0 ; i < rowids.length ; i++) {
		var rowid = rowids[i];
		var oRow = this.getRow(rowid);
		this.delRow(oRow);
	}
	this.showPage(this.getValue());
}


/**
 * 删除一条记录
 * @param {} rowNum 行号
 */
ComponentDataGrid.prototype.delRecordByNum = function(rowNum) {
	var oRow = this.getRowByNum(rowNum);
	this.delRow(oRow);
	this.showPage(this.getValue());
}

/**
 * 删除多条记录
 * @param {} rowNums 行号数组
 */
ComponentDataGrid.prototype.delRecordByNums = function(rowNums) {
	for (var i = 0 ; i < rowNums.length ; i++) {
		var rowNum = rowNums[i];
		var oRow = this.getRowByNum(rowNum);
		this.delRow(oRow);
	}
	this.showPage(this.getValue());
}

/**
 * 删除行
 * @param oRow
 */
ComponentDataGrid.prototype.delRow = function(oRow) {
	if (oRow) {
		var rowid = oRow.getRowID();
		delete this._records[rowid];
		var rowNum = oRow.getRowNum();
		delete this._cache[rowNum];
		$(oRow.getHTML()).remove();
	}
}

/**
 * 填充表格一行，寻找表格空行(fillBlankRow = true)，填充数据
 * @param {} oData
 */
ComponentDataGrid.prototype.fillRecord = function(oData) {
	var oRows = this.getRecords();
    for (var i = 0 ; i < oRows.length ; i++) {
        var oRow = oRows[i];
        if (this.isEmptyRow(oRow)) {
        	this._count++;
            oRow.setValue(oData);
            return;
        }
    }
}

/**
 * 清空表格
 */
ComponentDataGrid.prototype.clear = function() {
	$("#no-result", this.getHTML()).remove();
	var aRecords = this.getRecords();
	for (var i = 0; i < aRecords.length; i++) {
		$(aRecords[i].getHTML()).detach();
	}
	delete this._data;
	this._data = new Array();
	delete this._records;
	this._records = new Object();
}

/**
 * 查询并显示表格
 * @param {} p_oParams
 * @param {} oCallBack 如果不为空，则异步加载数据. 加载完成回调方法
 * @param {} sSort 排序字段 如:person_name:asc
 */
ComponentDataGrid.prototype.queryAndDisplay = function(oParams, 
	oCallBack, sSort) {
	if (oParams) {
		this._queryParam = this.buildParam(oParams);
	}
	if (sSort) {
		this._sort = sSort;
	}
	this.goPage(1, oCallBack);
}

/**
 * 建立条件
 * @param {} oParam
 * @return {}
 */
ComponentDataGrid.prototype.buildParam = function(oParam) {
	if (this._fixParam) {
		for (var sCont in this._fixParam) {
			oParam[sCont] = this._fixParam[sCont]
		}
	}
	return oParam;
}

ComponentDataGrid.prototype.reshow = function() {
	this.goPage(this._currentPage);
}

ComponentDataGrid.prototype.getRecords = function() {
	var aRecords = new Array();
	for (var record in this._records) {
		aRecords.push(this._records[record]);
	}
    return aRecords;
}

ComponentDataGrid.prototype.getRecordSize = function() {
    return this.getRecords().length;
}

/**
 * 排序记录集
 */
ComponentDataGrid.prototype.orderRecord = function() {
    //排序后数据
    oOrderRecords = new Object();
    var size = this.getRecordSize();
    for (var i = 0 ; i < size ; i++) {
        var oRecord = this.getOrderRecordByNum(i);
        oOrderRecords[oRecord.getData().id] = oRecord;
    }
    this._records = oOrderRecords;
}

/**
 * 获得排序的record. 排序记录集使用。
 * @param num
 * @returns {*}
 */
ComponentDataGrid.prototype.getOrderRecordByNum = function(num) {
    var records = this.getRecords();
    for (var i = 0 ; i < records.length ; i++) {
        var oRecord = records[i];
        if (oRecord.getRowNum() == num) {
            var id = oRecord.getData().id;
            delete this._records[id];
            return oRecord;
        }
    }
}


/**
 * 获得总记录条数
 * @return {}
 */
ComponentDataGrid.prototype.getTotalRecord = function() {
	return this._count;
}

ComponentDataGrid.prototype.getTotalPage = function() {
	var totalPage = parseInt(this._count / this._rowNum);
	if (this._count % this._rowNum != 0) {
		totalPage++;
	}
	return totalPage;
}

ComponentDataGrid.prototype.getCurrentPage = function() {
	return this._currentPage;
}

/**
 * @param {} iPageNum
 * @param {} oCallBack
 * @param {} unQuery 是否提交后台查询 setValue使用
 */
ComponentDataGrid.prototype.goPage = function(iPageNum, oCallBack, unQuery) {
	//翻页前调用事件
	this.triggerAttributeEvent("onpaging", iPageNum);
	debugger;
	var oRequest = new Object();
	if(typeof (this._queryParam) == "object") oRequest = this._queryParam;

	oRequest.rowcount = true;
	oRequest.rownum = this._rowNum;
	oRequest.ipageNum = iPageNum;
	var rowStart = this._rowNum * (iPageNum - 1);
	oRequest.start = rowStart;
	if (this._sort != "") {
		oRequest.sort = this._sort;
	}
	var othis = this;
	
	this.getDataSource().queryData(oRequest, true, function(oResult) {
		var oRecords = oResult.records;
		if(!oRecords) return;
		if (!oResult.count)
			othis._count = oResult.records.length;
		else
			othis._count = oResult.count;
			
		var data;
		if (oRecords.length > othis._rowNum) {
			data = oRecords.slice((iPageNum - 1) * othis._rowNum);
		} else {
			data = oRecords;
		}
		othis.triggerAttributeEvent("beforeshow", oRecords);
		othis.showPage(data);
		othis._data = oRecords;
		if (oCallBack) {
			oCallBack(othis, data, oResult);
		}
		// 调用分页控件的初始化分页标签
		if (othis._pageHandler) {
			othis._pageHandler.postMessage({
                id:"MSG_TABLEPAGETOOL_INITPAGE"
            })
		}
		othis.triggerAttributeEvent("onload", data);
	}, unQuery);
	this._currentPage = iPageNum;
}

ComponentDataGrid.prototype.getCount = function() {
	return this._count;
}

ComponentDataGrid.prototype.setCount = function(count) {
	this._count = count;
}

ComponentDataGrid.prototype.getData = function() {
	return this._data;
}

ComponentDataGrid.prototype.getValue = function() {
	var arrData = new Array();
	var arrRecord = this.getRecords();
	for (var i = 0; i < arrRecord.length; i++) {
		var oData = arrRecord[i].getData();
		if (!this.isEmptyObj(oData)) {
			arrData.push(oData);
		}
	}
	return arrData;
}

ComponentDataGrid.prototype.addValue = function(arrData) {
	var oData = this.getData();
	for (var i = 0; i < arrData.length; i++) {
		oData.push(arrData[i]);
	}
	this.setValue(oData);
}

ComponentDataGrid.prototype.initTable = function() {
	this.setValue();
}

ComponentDataGrid.prototype.setValue = function(arrData) {
	if (!arrData || (arrData == "" && typeof(arrData.length) == "undefined"))
		arrData = new Array();
	var oData = {
		records : arrData,
		count : arrData.length
	};
	this.setData(oData);
	this.goPage(1, null, true);
}

/**
 * 获得有数据的行
 */
ComponentDataGrid.prototype.getDataRowCount = function() {
	var oRows = this.getRecords();
	var num = 0 ; 
	for (var i = 0 ; i < oRows.length ; i++) {
		var oRow = oRows[i];
		if (!this.isEmptyRow(oRow)) {
			num++;
		}
	}
	return num;
}
/**
 * 获得空行的个数
 */
ComponentDataGrid.prototype.getEmptyRowCount = function() {
    var oRows = this.getRecords();
    var num = 0 ;
    for (var i = 0 ; i < oRows.length ; i++) {
        var oRow = oRows[i];
        if (this.isEmptyRow(oRow)) {
            num++;
        }
    }
    return num;
}

ComponentDataGrid.prototype.isEmptyTable = function() {
	var oRows = this.getRecords();
	for (var i = 0 ; i < oRows.length ; i++) {
		var oRow = oRows[i];
		if (!this.isEmptyRow(oRow)) {
			return false;
		}
	}
	return true;
}

/**
 * 是否空行
 * @param {} oRow
 * @return {}
 */
ComponentDataGrid.prototype.isEmptyRow = function(oRow) {
	var oData = oRow.getValue();
	return this.isEmptyObj(oData);
}

ComponentDataGrid.prototype.isEmptyObj = function(oData) {
	for (var i in oData) {
		if (i == "rownum") {
			continue;
		}
		if (typeof(oData[i]) == "object") {
			var flag = this.isEmptyObj(oData[i]);
			if (!flag) return false;
		} else {
			if (oData[i] && oData[i] != "") {
				return false;
			}
		}
	}
	return true;
}

/**
 * 获得所有行id数组
 * 
 * @return {}
 */
ComponentDataGrid.prototype.getDataIDs = function() {
	var ids = new Array();
	for (var id in this._records) {
		ids.push(id);
	}
	return ids;
}

/**
 * 获得行控件
 * 
 * @param {} rowid
 * @return {}
 */
ComponentDataGrid.prototype.getRow = function(rowid) {
	return this._records[rowid];
}

/**
 * 获得行控件通过行号
 * 
 * @param {}  num
 * @return {}
 */
ComponentDataGrid.prototype.getRowByNum = function(num) {
	return this.getRecords()[num];
}

/**
 * 获得行数据
 * 
 * @param {} rowid
 * @return {}
 */
ComponentDataGrid.prototype.getRowData = function(rowid) {
	return this._records[rowid].getData();
}

/**
 * 获得行数据通过行号
 * 
 * @param {} num
 * @return {}
 */
ComponentDataGrid.prototype.getRowDataByNum = function(num) {
	return this.getRecords()[num].getData();
}

/**
 * 上移行
 * @param {} rowNum 当前行号
 */
ComponentDataGrid.prototype.upRow = function(rowNum) {
	if (rowNum == 0) return false;
	var oRow = this.getRowByNum(rowNum);
	var oPreRow = this.getRowByNum(rowNum - 1);
	oRow.setRowNum(rowNum - 1);
	oPreRow.setRowNum(rowNum);
    this.orderRecord();
    this.showPage(this.getValue());
}

/**
 * 下移行
 * @param {} rowNum
 */
ComponentDataGrid.prototype.downRow = function(rowNum) {
	var oRecords = this.getRecords();
	if (rowNum == oRecords.length - 1) return false;
    var oRow = this.getRowByNum(rowNum);
    var oNextRow = this.getRowByNum(rowNum + 1);
    oRow.setRowNum(rowNum + 1);
    oNextRow.setRowNum(rowNum);
    this.orderRecord();
    this.showPage(this.getValue());
}

/**
 * @brief 设置表格不可编辑
 */
ComponentDataGrid.prototype.setEnable = function() {
	for (var id in this._records) {
		this._records[id].setEnable();
	}
	this._disable = false;
}

/**
 * @brief 设置表格不可编辑
 * @params state boolean 如果为true，则所有控件不可编辑. 默认只有path属性控件才不可编辑。
 */
ComponentDataGrid.prototype.setDisable = function(state) {
	for (var id in this._records) {
		this._records[id].setDisable(state);
	}
	this._disable = true;
}

// 获取每页显示条数
ComponentDataGrid.prototype.getRowNum = function() {
	return this._rowNum;
}

// 设置每页显示条数
ComponentDataGrid.prototype.setRowNum = function(rowNum) {
	this._rowNum = rowNum;
	this.goPage(1);
}

/**
 * 获得最后一次查询条件
 * @return {}
 */
ComponentDataGrid.prototype.getLastQueryParam = function() {
	return this._queryParam;
}

/**
 * 选择或反选id = rowid指定的行。若onselectrow设置为true (缺省)
 * 则触发onSelectRow事件，否则不触发。
 * @param {} rowId
 * @param {} onselectrow
 * @param {} isClick 是否是点击
 */
ComponentDataGrid.prototype.setSelection = function(rowId, onselectrow, isClick) {
	if (typeof(onselectrow) == "undefined") onselectrow = true;
	if (!isClick) {
		for (var id in this._records) {
			if (rowId == id) {
				var oSelectBtn = this._records[id].getElementByPath("rowselect");
				if (oSelectBtn.hasChecked()) {
					oSelectBtn.setUnChecked();
				} else {
					oSelectBtn.setChecked();
				}
			}
		}
	}
	//控制全选反选按钮
	this.controlSelectBtn();
	if (onselectrow) {
		this.triggerAttributeEvent("onselectrow", rowId, this.getSelection());
	}
}

/**
 * 控制全选反选按钮
 */
ComponentDataGrid.prototype.controlSelectBtn = function() {
	for (var id in this._records) {
		var oSelectBtn = this._records[id].getElementByPath("rowselect");
		if (!oSelectBtn.hasChecked()) {
			this._checkAllBtn.setUnChecked();
			return;
		}
	}
	this._checkAllBtn.setChecked();
}

/**
 * 设置全选反选按钮
 */
ComponentDataGrid.prototype.setCheckAllButton = function(oCheckBox) {
	this._checkAllBtn = oCheckBox;
}

/**
 * 判断是否显示记录数
 */
ComponentDataGrid.prototype.isShowRowNum = function() {
	return this._isShowRowNum;
}

/**
 * 设置全选反选按钮
 */
ComponentDataGrid.prototype.hasCheckAllButton = function() {
	if (this._checkAllBtn) {
		return true;
	}
	return false;
	
}

	
/**
 * 全选或反选行
 */
ComponentDataGrid.prototype.resetSelection = function() {
	if (!this._checkAllBtn) return;
	if (this._checkAllBtn.hasChecked()) {
		for (var id in this._records) {
			var oSelectBtn = this._records[id].getElementByPath("rowselect");
			oSelectBtn.setChecked();
		}
		this._checkAllBtn.setChecked();
	} else {
		for (var id in this._records) {
			var oSelectBtn = this._records[id].getElementByPath("rowselect");
			oSelectBtn.setUnChecked();
		}
		this._checkAllBtn.setUnChecked();
	}
	this.triggerAttributeEvent("onselectall", this.getSelection());
}

/**
 * 获得多行选中. 复选框
 * @return {}
 */
ComponentDataGrid.prototype.getSelection = function() {
	var ids = [];
	for (var id in this._records) {
		var oSelectBtn = this._records[id].getElementByPath("rowselect");
		if (oSelectBtn.hasChecked()) {
			ids.push(id);
		}
	}
	return ids;
}

/**
 * 导出excel
 * @param oParam
 */
ComponentDataGrid.prototype.exportExcel = function(oParam,totalcount) {
	if (this._oQueryParam && typeof(oParam) == "undefined") {
		oParam = this._oQueryParam;
	}
	if (typeof(oParam) == "undefined") {
		oParam = {};
	}
	if(!totalcount) totalcount = this.getCount();
	this.getDataSource().exportExcel(oParam,totalcount);
	
	WinUtil.alert("数据较多,请耐心等待!导出过程可进行其他操作!")
}


/**
 * 获得选中行
 */
ComponentDataGrid.prototype.getSelectionRow = function() {
	var rows = [];
	for (var id in this._records) {
		var oSelectBtn = this._records[id].getElementByPath("rowselect");
		if (oSelectBtn.hasChecked()) {
			rows.push(this._records[id]);
		}
	}
	return rows;
}

